package cn.dansj.handler.interfaces;

import cn.dansj.annotation.MarkAsApi;
import cn.dansj.entity.User;
import cn.dansj.common.utils.enums.ResponseCode;
import cn.dansj.exception.InterfaceResponseException;
import cn.dansj.service.UserService;
import cn.dansj.common.context.ApplicationContextProvider;
import cn.dansj.common.utils.crypt.Pbkdf2Sha256;
import cn.dansj.handler.InterfaceHandler;
import cn.dansj.utils.project.ProjectUtils;

import java.util.Map;

@SuppressWarnings("all")
@MarkAsApi
public class UserRegister extends InterfaceHandler {
    @Override
    public Object execute(Map<String, Object> paramsMap) {
        String nickname = paramsMap.getOrDefault("nickname", "").toString();
        String code = paramsMap.getOrDefault("code", "").toString();
        String mail = paramsMap.getOrDefault("mail", "").toString();
        String password = paramsMap.getOrDefault("password", "").toString();
        String decryptPassword = ProjectUtils.decryptByPrivateKey(password);

        UserService userService = ApplicationContextProvider.getBean(UserService.class);
        User user = userService.getUser(mail);
        if (user != null) {
            throw new InterfaceResponseException(ResponseCode.Error.getStatusCode(), "邮箱已存在");
        }
        String key = "captcha@" + mail + "@register";
        String redisCode = redisUtils.getString(key);
        boolean check = code.equals(redisCode);
        redisUtils.delete(key);
        if (!check) {
            throw new InterfaceResponseException(ResponseCode.Error.getStatusCode(), "邮箱验证码错误");
        }
        User registerUser = ProjectUtils.getEmptyUser();
        registerUser.setNickName(nickname);
        registerUser.setPassword(Pbkdf2Sha256.encode(decryptPassword));
        registerUser.setMail(mail);
        userService.save(registerUser);
        ProjectUtils.updateUserInterfaceTokenInfo(registerUser);
        return "用户注册成功";
    }
}